package com.clwl.supervise.superviseapp.entity.scan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TjFoodTypeTree {

    private String id;

    private String parentId;

    private String text;

    private String value;

    private List<TjFoodTypeTree> children = null;

    public TjFoodTypeTree(String id, String parentId, String text,String code) {
        this.id = id;
        this.parentId = parentId;
        this.text = text;
        this.value = code;
    }

    public String getId() {
        return id;
    }

    public String getParentId() {
        return parentId;
    }

    public String getText() {
        return text;
    }

    public String getValue() {
        return value;
    }

    public List<TjFoodTypeTree> getChildren() {
        return children;
    }

    public void addChild(TjFoodTypeTree child) {
        if(children == null){
            children = new ArrayList<>();
        }
        children.add(child);
    }

    public static List<TjFoodTypeTree> buildTree(List<TjFoodTypeTree> nodes) {
        Map<String, TjFoodTypeTree> nodeMap = new HashMap<>();
        List<TjFoodTypeTree> roots = new ArrayList<>();

        // 将所有节点加入Map中
        for (TjFoodTypeTree node : nodes) {
            nodeMap.put(node.getId(), node);
        }

        // 遍历所有节点，将每个节点加入其父节点的children列表中
        for (TjFoodTypeTree node : nodes) {
            if (node.getParentId() == null) { // 根节点
                roots.add(node);
            } else {
                TjFoodTypeTree parent = nodeMap.get(node.getParentId());
                parent.addChild(node);
            }
        }

        return roots;
    }

    public static void traverse(List<TjFoodTypeTree> nodes, int depth) {
        for (TjFoodTypeTree node : nodes) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < depth; i++) {
                sb.append("  ");
            }
            sb.append(node.getText());
            System.out.println(sb.toString());
            traverse(node.getChildren(), depth + 1);
        }
    }
}
